// pages/place_order/place_order.js
var common = require("../../../common/common.js").common;

var leader = require("../../../common/leader.js").leader;

var QQMapWX = require("../../../sdk/qqmap-wx-jssdk.min.js");

const {$Toast: $Toast} = require("../../../dist/base/index");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        defferNum: "立即购买",
        title: "商品订单",
        num_total: 1,
        //商品数量
        componentStyle: {
            navigationTitle: "",
            goBack: true
        },
        myleaderinfo: {
            leader_id: -1
        },
        tmplIds: [],
        subscribeMessage: true,
        //立即支付-订阅消息
        subscribeMessage_add: true,
        //增加商品
        currentOptions: {}
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.setData({
            product_id: options.id,
            //此处增加  设置页面参数
            currentOptions: options
        });
        let that = this;
        leader.getMyLeaderInfo();
        //公用方法团长请求
                that.getProData();
        that.getBase();
        //获取tempIds
                that.getTempIds();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        let that = this;
        const system = wx.getSystemInfoSync().system;
        const isIOS = system.includes("iOS");
        that.setData({
            isIOS: isIOS
        });
        that.getRecieverInfo();
    },
    /** 
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    onPageScroll(e) {},
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    apptitle: res.extra.title,
                    style: res.extra.style,
                    leader_change: res.extra.l_change,
                    leader_express: res.extra.l_express,
                    rp_name: res.extra.rp_name,
                    order_start: res.extra.order_start,
                    order_start_switch: res.extra.order_start_switch,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    communityName: res.extra.community_title ? res.extra.community_title : "社区"
                });
                //处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
                //设置模块颜色
                                var componentStyle = that.data.componentStyle;
                that.setData({
                    componentStyle: {
                        ...componentStyle,
                        color_main: !res.extra.color_main ? "#FE513B" : res.extra.color_main
                    }
                });
            }
        });
    },
    getProData: function() {
        var that = this;
        let params = {
            product_id: that.data.product_id,
            //此处增加 solit_id参数
            solit_id: that.data.currentOptions.solit_id
        };
        let currentOptions = this.data.currentOptions;
        common.request({
            endpoint: "Localbusiness/product/product-detail",
            method: "post",
            data: params,
            success: res => {
                console.log(res);
                if (!res.extra.using_expire_in) {
                    res.extra.using_expire_in = "";
                }
                let banner = res.extra.banner.split(",");
                that.setData({
                    business_id: res.extra.business_info.id,
                    //本地商户id
                    business_name: res.extra.business_info.name,
                    //商家名称
                    business_phone: res.extra.business_info.phone,
                    //商家电话
                    business_address: res.extra.business_info.address,
                    //商家地址
                    product_id: res.extra.id,
                    //购买商品id
                    product_name: res.extra.product_name,
                    //商品名称
                    purchase_limit: res.extra.purchase_limit,
                    //限购数量
                    using_expire_in: res.extra.using_expire_in.split(",").join("~"),
                    //使用有效期
                    cover: res.extra.cover,
                    //商品封面图
                    sale_price: res.extra.sale_price,
                    //销售价格
                    market_price: res.extra.market_price,
                    //市场价格
                    can_amount: res.extra.can_amount,
                    //可以购买的数量
                    has_amount: res.extra.has_amount,
                    //已经购买的数量
                    total_price: parseFloat(that.data.num_total * res.extra.sale_price).toFixed(2),
                    banner: banner[0]
                });
            }
        });
    },
    reduce: function() {
        let num_total = this.data.num_total;
        if (num_total > 1) {
            num_total--;
        }
        this.setData({
            num_total: num_total,
            total_price: parseFloat(num_total * this.data.sale_price).toFixed(2)
        });
    },
    add: function() {
        let that = this;
        that.add_ch();
        if (that.data.subscribeMessage_add) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {
                    console.log(err);
                }
            });
        }
    },
    add_ch: function() {
        let purchase_limit = this.data.purchase_limit;
        let num = this.data.num_total;
        if (!purchase_limit) {
            //不限购
            if (num < this.data.can_amount) {
                num++;
            } else {
                wx.showModal({
                    title: "提示",
                    content: "库存不足"
                });
            }
        } else {
            if (num < this.data.can_amount) {
                num++;
            } else {
                wx.showModal({
                    title: "提示",
                    content: "你已经购买了" + num + "件，无法继续购买"
                });
            }
        }
        this.setData({
            num_total: num,
            total_price: parseFloat(num * this.data.sale_price).toFixed(2)
        });
    },
    confirmOrder: function() {
        let that = this;
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {
                    console.log(err);
                },
                complete() {
                    that.confirmOrder_ch();
                }
            });
        } else {
            that.confirmOrder_ch();
        }
    },
    confirmOrder_ch: function() {
        let that = this;
        if (!that.data.recieverInfo.receiverName || !that.data.recieverInfo.phone) {
            wx.showModal({
                title: "提示",
                content: "姓名和电话不能为空！",
                showCancel: false
            });
            return;
        }
        if (!/^1[3456789]\d{9}$/.test(that.data.recieverInfo.phone)) {
            wx.showModal({
                title: "提示",
                content: "请输入正确的手机号码！",
                showCancel: false
            });
            return;
        }
        common.request({
            endpoint: "Localbusiness/order/pay",
            method: "post",
            data: {
                name: that.data.recieverInfo.receiverName,
                phone: that.data.recieverInfo.phone,
                business_id: that.data.business_id,
                product_id: that.data.product_id,
                amount: that.data.num_total,
                remark: that.data.remark,
                leader_id: that.data.myleaderinfo.leader_id,
                //此处增加 solit_id参数
                solit_id: that.data.currentOptions.solit_id
            },
            success: res => {
                console.log(res);
                that.payWay(res, res.order_no);
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    },
    /** 
   * 记录 input 的值
   * e: object 
   */
    recordValue: function(e) {
        let key = e.currentTarget.dataset.name;
        let value = e.detail.value;
        console.log(key + "," + value);
        this.setData({
            [key]: value
        });
    },
    /**
   * 
   * 微信支付
   * 
   */
    payWay(res, order_no) {
        wx.requestPayment({
            timeStamp: res.pay.timeStamp,
            nonceStr: res.pay.nonceStr,
            package: res.pay.package,
            signType: res.pay.signType,
            paySign: res.pay.paySign,
            success: function(res) {
                console.log(res);
                wx.showToast({
                    title: "支付成功",
                    icon: "success",
                    mask: true,
                    duration: 3e3,
                    success: function(res) {
                        wx.showToast({
                            title: "购买成功！",
                            icon: "success",
                            success: function() {
                                setTimeout(function() {
                                    wx.reLaunch({
                                        url: "/localLifePackage/pages/order/order"
                                    });
                                }, 500);
                            }
                        });
                    }
                });
            },
            fail: function(res) {
                wx.navigateTo({
                    url: "/localLifePackage/pages/order/order"
                });
            },
            complete: function(res) {
                wx.reLaunch({
                    url: "/localLifePackage/pages/order/order"
                });
            }
        });
    },
    getRecieverInfo: function() {
        let that = this;
        var reciever = app.globalData.reciever;
        if (reciever) {
            that.setData({
                recieverInfo: {
                    ...reciever,
                    url: "/addressManagerPackage/pages/addressList/addressList"
                }
            });
        } else {
            common.request({
                endpoint: "member/def_address",
                method: "post",
                data: {},
                success(res) {
                    console.log(res, "reciever");
                    var data = res.extra;
                    if (data) {
                        var recieverInfo = {
                            receiverName: data.name,
                            //收货人名称
                            phone: data.phone,
                            //电话
                            address: data.city + " " + data.area,
                            //收货地址
                            city: data.city,
                            area: data.area,
                            wwb_street_id: data.wwb_street_id,
                            url: "/addressManagerPackage/pages/addressList/addressList"
                        };
                        app.globalData.reciever = recieverInfo;
                        that.setData({
                            recieverInfo: recieverInfo
                        });
                    } else {
                        var recieverInfo = {
                            url: "/addressManagerPackage/pages/addressList/addressList"
                        };
                        that.setData({
                            recieverInfo: recieverInfo
                        });
                    }
                },
                fail(err) {}
            });
        }
    },
    //获取tempIds
    getTempIds: function() {
        var that = this;
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                console.log(res);
                let tmplIds = [];
                let subscribeMessage = true;
                let subscribeMessage_add = true;
                res.extra.map(v => {
                    if ((v.type == "23" || v.type == "27") && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                    subscribeMessage_add = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage,
                    subscribeMessage: subscribeMessage_add
                });
            }
        });
    }
});